package com.shengchang.hu.supervision.UI;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.posapi.PosApi;
import android.posapi.PosApi.OnCommEventListener;
import android.posapi.PrintQueue;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DamagedActivity extends BaseActivity {


    InBoundBar checkedbar;
    private PosApi mPosSDK = null;
    private PrintQueue mPrintQueue = null;

    /*扫描*/
    MediaPlayer player;
    private byte mGpioPower = 0x1E;// PB14
    private byte mGpioTrig = 0x29;// PC9

    private ScanBroadcastReceiver scanBroadcastReceiver;
    private  static  final  String  Rubbish_API=Contants.Rubbish_API;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_damaged);
        checkedbar=findViewById(R.id.checkedbar);
        checkedbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initPos();


        }

    private void initScan() {
        //注册获取扫描信息的广播接收器
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(PosApi.ACTION_POS_COMM_STATUS);
        registerReceiver(receiver, mFilter);
        // 物理扫描键按下时候会有动作为ismart.intent.scandown的广播发出，可监听该广播实现触发扫描动作
        scanBroadcastReceiver = new ScanBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ismart.intent.scandown");
        this.registerReceiver(scanBroadcastReceiver, intentFilter);

        // 扫描提示音
        player = MediaPlayer.create(getApplicationContext(),
                R.raw.beep);

    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            initScan();


                        }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }

            }
        }).start();
        }

    /**
     * 物理SCAN按键监听
     */
    boolean isScan = false;

    class ScanBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //监听到SCAN按键按下广播，执行扫描

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ScanDomn();

                            }
                        });
                    } catch (InputMismatchException e) {
                        e.printStackTrace();
                    }

                }
            }).start();


        }
    }

    private void initPos() {
        // 获取PosApi实例
        mPosSDK = PosApi.getInstance(this);
        // 根据型号进行初始化mPosApi类
        if (Build.MODEL.contains("LTE")
                || Build.DISPLAY.contains("3508")
                || Build.DISPLAY.contains("403")
                || Build.DISPLAY.contains("35S09")) {
            mPosSDK.initPosDev("ima35s09");
        } else if (Build.MODEL.contains("5501")) {
            mPosSDK.initPosDev("ima35s12");
        } else {
            mPosSDK.initPosDev(PosApi.PRODUCT_MODEL_IMA80M01);
        }

        //监听初始化回调结果
        mPosSDK.setOnComEventListener(mCommEventListener);

    }

    /**
     * 初始化
     */
OnCommEventListener mCommEventListener = new OnCommEventListener() {
        @Override
        public void onCommState(int cmdFlag, int state, byte[] resp, int respLen) {
            // TODO Auto-generated method stub
            switch (cmdFlag) {
                case PosApi.POS_INIT:
                    if (state == PosApi.COMM_STATUS_SUCCESS) {
                        Toast.makeText(getApplicationContext(), "设备初始化成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "设备初始化失败",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };



    /**
     * 执行扫描，扫描后的结果会通过action为PosApi.ACTION_POS_COMM_STATUS的广播发回
     */
    public void ScanDomn() {
        if (!isScan) {
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 200);
        } else {
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 200);
        }
    }

    Handler handler = new Handler();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            // 强制关闭扫描头
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            isScan = false;
        }
    };

    /**
     * 扫描信息获取
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equalsIgnoreCase(PosApi.ACTION_POS_COMM_STATUS)) {
                // 串口标志判断
                int cmdFlag = intent.getIntExtra(PosApi.KEY_CMD_FLAG, -1);
                // 获取串口返回的字节数组
                byte[] buffer = intent
                        .getByteArrayExtra(PosApi.KEY_CMD_DATA_BUFFER);
                switch (cmdFlag) {
                    // 如果为扫描数据返回串口
                    case PosApi.POS_EXPAND_SERIAL3:
                        if (buffer == null)
                            return;
                        try {
                            // 将字节数组转成字符串
                            final String str = new String(buffer, "UTF-8");
                            // 开启提示音，提示客户条码或者二维码已经被扫到
                            player.start();
                            if (str != null) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        try {

                                            Handler handler = new Handler(Looper.getMainLooper());
                                            handler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    showProgressDialog();
                                                    BulouCodeRequest(str);

                                                }
                                            });
                                        } catch (InputMismatchException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }).start();
                            } else {
                                showShortToast("扫码失败，请重新扫描");
                            }


                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                }
                // 扫描完本次后清空，以便下次扫描
                buffer = null;
            }
        }
    };

    private void BulouCodeRequest(String str) {
        OkHttpClient moKhttp = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("rubbishCodes", str)
                .build();
        Request request = new Request.Builder()
                .url(Rubbish_API)
                .post(formBody)
                .build();
        Log.d("Cntralized_API", Rubbish_API + "?id=" + App.getApp().getToken() + "&rubbishCodes=" + str);
        Call call = moKhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                            final  String buloustr=response.body().string();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    bulouReponse(buloustr);
                                }
                            });
            }
        });


    }

    private void bulouReponse(String buloustr) {
        try {
            JSONObject Departmentjson = new JSONObject(buloustr);
            String DepartmentMsg = Departmentjson.getString("message");
            if (DepartmentMsg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("网络请求异常");
            } else if (DepartmentMsg.equals("20005")) {
                dismissProgressDialog();
                showShortToast("登记成功");
                }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销获取扫描数据的广播
        unregisterReceiver(receiver);
        // 注销物理SCAN按键的接收广播
        unregisterReceiver(scanBroadcastReceiver);

        if (mPrintQueue != null) {
            // 打印队列关闭
            mPrintQueue.close();
        }

        // 关闭下层串口以及打印机
        mPosSDK.closeDev();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


    }
    @Override
    public void onBackPressed() {
        finish();
    }

}
